package com.android.samples.mediastore.hms.drive

import android.annotation.SuppressLint
import android.content.Context
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.android.samples.mediastore.HMSDriveApp
import com.android.samples.mediastore.hms.drive.operate.FilesManager
import com.android.samples.mediastore.hms.drive.operate.UserInfoHelper
import com.android.samples.mediastore.hms.drive.utils.MimeType
import com.huawei.cloud.services.drive.model.File
import dagger.hilt.android.lifecycle.HiltViewModel
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class DriveViewModel @Inject constructor(private val filesManagerHelper: FilesManager) :
    ViewModel() {

    private val _textLiveData = MutableLiveData("")
    val textLiveData: LiveData<String> = _textLiveData

    private val _filesLiveData = MutableLiveData<List<File>?>()
    val filesLiveData: LiveData<List<File>?> = _filesLiveData
    private val TAG = "DriveViewModel"

    @SuppressLint("StaticFieldLeak")
    @Inject
    @ApplicationContext
    lateinit var context: Context


    @Inject
    lateinit var userInfoHelper: UserInfoHelper


    fun getUserInformation() {
        viewModelScope.launch {
            userInfoHelper.apply {
                getAbout()?.let {
                    checkUpdateProtocol(context, it)
                    _textLiveData.value = "${it.user.displayName}  \n" +
                            "空间总容量:${it.storageQuota.userCapacity} \n" +
                            "空间已使用容量:${it.storageQuota.usedSpace} \n" +
                            "允许上传的最大文件:${it.maxFileUploadSize}"
                }
            }
            Log.d(TAG, "getUserInformation: 完成")
        }
    }

    fun loadPicturesFromRoot() {
        loadPicturesJob = viewModelScope.launch {
            val files = filesManagerHelper.getFileList("'root' in parentFolder", "folder", 100, "*")
            _filesLiveData.value = files
        }
    }


    private val allCloudFiles = mutableListOf<File>()


    fun loadAllPictures() {
        loadPicturesJob = viewModelScope.launch {
            loadAllPicturesFrom("root")
        }
    }

    private suspend fun loadAllPicturesFrom(FolderId: String) {
        val files = filesManagerHelper.getFileList(
            "'$FolderId' in parentFolder",
            "folder",
            100,
            "*"
        )
        if (files != null) {
            allCloudFiles.addAll(files)
        }

        files?.forEach {
            if (it.mimeType == MimeType.FOLDER) {
                loadAllPicturesFrom(it.id)
            }
        }
    }


    private lateinit var loadPicturesJob: Job
    private val mutableList = mutableListOf<File>()
    fun loadPicturesFromFolder(FolderId: String) {
        if (loadPicturesJob.isActive) {
            loadPicturesJob.cancel()
        }
        loadPicturesJob = viewModelScope.launch {
            mutableList.clear()
            _filesLiveData.value = mutableList
            val files =
                filesManagerHelper.getFileList(
                    "'$FolderId' in parentFolder",
                    "folder",
                    100,
                    "*"
                )
            _filesLiveData.value = files
        }
    }

    fun download(file: File) {
        viewModelScope.launch {
            filesManagerHelper.downLoadFile(file)
        }
    }

    fun delete(file: File) {
        viewModelScope.launch {
            filesManagerHelper.deleteFile(file)
            _filesLiveData.value = _filesLiveData.value!!.toMutableList().apply { remove(file) }
        }
    }


    fun createFileTest() {
        val dirName = "批量上传图片"
        viewModelScope.launch {
            loadAllPicturesFrom("root")
            val dirId = getDirIdByName(dirName)
            if (dirId != null) {
                HMSDriveApp.images!!.forEach {
                    viewModelScope.launch {

                        filesManagerHelper.createFile(_textLiveData, dirId, it.path, allCloudFiles)
                    }
                }
            }
        }
    }

    private suspend fun getDirIdByName(dirName: String): String? {
        var dirId: String? = null
        filesManagerHelper.getFileList(
            "mimeType = '${MimeType.FOLDER}' and fileName='${dirName}'",
            "fileName",
            10,
            "*"
        )?.apply {
            dirId = if (isNotEmpty()) {
                get(0).id
            } else {
                Log.d(TAG, "dirId = null")
                filesManagerHelper.createDirectory(dirName)?.id
            }
        }
        return dirId
    }


}


